import React, { useState } from 'react'
import useDialogState from '@/hooks/use-dialog-state'
import { type Upload } from '../data/schema'

type UploadsDialogType = 'invite' | 'add' | 'edit' | 'delete'

interface UploadsContextType {
  open: UploadsDialogType | null
  setOpen: (str: UploadsDialogType | null) => void
  currentRow: Upload | null
  setCurrentRow: React.Dispatch<React.SetStateAction<Upload | null>>
}

const UploadsContext = React.createContext<UploadsContextType | null>(null)

interface Props {
  children: React.ReactNode
}

export default function UploadsProvider({ children }: Props) {
  const [open, setOpen] = useDialogState<UploadsDialogType>(null)
  const [currentRow, setCurrentRow] = useState<Upload | null>(null)

  return (
    <UploadsContext.Provider value={{ open, setOpen, currentRow, setCurrentRow }}>
      {children}
    </UploadsContext.Provider>
  )
}

// eslint-disable-next-line react-refresh/only-export-components
export const useUploads = () => {
  const uploadsContext = React.useContext(UploadsContext)

  if (!uploadsContext) {
    throw new Error('useUploads has to be used within <UploadsContext>')
  }

  return uploadsContext
}
